package cn.itsource.config;

import cn.itsource.constants.Constants;
import cn.itsource.constants.RConst;
import cn.itsource.mapper.LoginMapper;
import cn.itsource.mapper.RoleMapper;
import cn.itsource.pojo.domain.Login;
import cn.itsource.pojo.domain.Role;
import cn.itsource.utils.IdUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 监听器在项目启动时初始化管理员
 */


@Component
public class BootstrapListener  implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private AdminConfig adminConfig;

    @Autowired
    private RoleMapper roleMapper;


    @Autowired
    private PasswordEncoder passwordEncoder;

	@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        LambdaQueryWrapper<Login> wrapper = new LambdaQueryWrapper<Login>().eq(Login::getType, RConst.Num.INT_0)
                .eq(Login::getUsername, adminConfig.getUsername());
        Login login = loginMapper.selectOne(wrapper);
        if(login==null){
            String pwd = passwordEncoder.encode(adminConfig.getPassword());
            Login initManager = new Login();
            initManager.setId(IdUtils.getId());
            initManager.setUsername(adminConfig.getUsername());
            initManager.setPassword(pwd);
            initManager.setType(RConst.Num.INT_0);
            initManager.setAvatar(adminConfig.getAvatar());
            initManager.setAdmin(true);
            initManager.setNickName(adminConfig.getNickName());
            initManager.setName(adminConfig.getName());
            initManager.setCreateTime(new Date());

            loginMapper.insert(initManager);
            LambdaQueryWrapper<Role> wrapper1 = new LambdaQueryWrapper<Role>().eq(Role::getSn, adminConfig.getRoleSN());
            Role role = roleMapper.selectOne(wrapper1);
            loginMapper.addLoginAndRole(initManager.getId(),role.getId(),IdUtils.getId());
        }

    }
}